package com.pig4cloud.pig.homecenter.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.homecenter.entity.HassAreaRegistryEntity;
import com.pig4cloud.pig.homecenter.entity.HassEntityRegistryEntity;
import com.pig4cloud.pig.homecenter.service.HassAreaRegistryService;
import com.pig4cloud.pig.homecenter.service.HassEntityRegistryService;
import com.pig4cloud.pig.homecenter.vo.SyncDevicesVO;
import com.pig4cloud.pig.homecenter.ws.HassWebsocketMessageUtils;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import com.pig4cloud.plugin.excel.annotation.RequestExcel;
import com.pig4cloud.pig.homecenter.entity.HassDeviceRegistryEntity;
import com.pig4cloud.pig.homecenter.service.HassDeviceRegistryService;

import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 设备数据
 *
 * @author pig
 * @date 2025-01-07 15:06:18
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/hassDeviceRegistry" )
@Tag(description = "hassDeviceRegistry" , name = "设备数据管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class HassDeviceRegistryController {

	private final  HassDeviceRegistryService hassDeviceRegistryService;

	private final HassAreaRegistryService hassAreaRegistryService;

	private final HassEntityRegistryService hassEntityRegistryService;

	/**
	 * 分页查询
	 * @param page 分页对象
	 * @param hassDeviceRegistry 设备数据
	 * @return
	 */
	@Operation(summary = "分页查询" , description = "分页查询" )
	@GetMapping("/page" )
	@PreAuthorize("@pms.hasPermission('homecenter_hassDeviceRegistry_view')" )
	public R getHassDeviceRegistryPage(@ParameterObject Page page, @ParameterObject HassDeviceRegistryEntity hassDeviceRegistry) {
		LambdaQueryWrapper<HassDeviceRegistryEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(StrUtil.isNotBlank(hassDeviceRegistry.getAreaId()),HassDeviceRegistryEntity::getAreaId,hassDeviceRegistry.getAreaId());
		wrapper.like(StrUtil.isNotBlank(hassDeviceRegistry.getCustomName()),HassDeviceRegistryEntity::getCustomName,hassDeviceRegistry.getCustomName());

		Page<HassDeviceRegistryEntity> res = hassDeviceRegistryService.page(page, wrapper);
		res.getRecords().forEach(item -> {
			LambdaQueryWrapper<HassAreaRegistryEntity> areaWrapper = Wrappers.lambdaQuery();
			areaWrapper.eq(HassAreaRegistryEntity::getUserId,item.getUserId());
			areaWrapper.eq(HassAreaRegistryEntity::getAreaId,item.getAreaId());
			HassAreaRegistryEntity area = hassAreaRegistryService.getOne(areaWrapper);
			item.setAreaName(area != null ? area.getName() : null);
		});
		return R.ok(res);
	}


	/**
	 * 通过条件查询设备数据
	 * @param hassDeviceRegistry 查询条件
	 * @return R  对象列表
	 */
	@Operation(summary = "通过条件查询" , description = "通过条件查询对象" )
	@GetMapping("/details" )
	@PreAuthorize("@pms.hasPermission('homecenter_hassDeviceRegistry_view')" )
	public R getDetails(@ParameterObject HassDeviceRegistryEntity hassDeviceRegistry) {
		List<HassDeviceRegistryEntity> devList = hassDeviceRegistryService.list(Wrappers.query(hassDeviceRegistry));
		devList.forEach(item -> {
			QueryWrapper<HassEntityRegistryEntity> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(HassEntityRegistryEntity::getDeviceId, item.getId())
					.eq(HassEntityRegistryEntity::getUserId, SecurityUtils.getUser().getId());
			List<HassEntityRegistryEntity> entityList = hassEntityRegistryService.list(queryWrapper);
			entityList.forEach(entity -> {
				HassWebsocketMessageUtils.configEntityRegistryGet(entity.getEntityId());
			});
		});

		return R.ok(devList);
	}

	/**
	 * 新增设备数据
	 * @param hassDeviceRegistry 设备数据
	 * @return R
	 */
	@Operation(summary = "新增设备数据" , description = "新增设备数据" )
	@SysLog("新增设备数据" )
	@PostMapping
	@PreAuthorize("@pms.hasPermission('homecenter_hassDeviceRegistry_add')" )
	public R save(@RequestBody HassDeviceRegistryEntity hassDeviceRegistry) {
		return R.ok(hassDeviceRegistryService.save(hassDeviceRegistry));
	}

	/**
	 * 修改设备数据
	 * @param hassDeviceRegistry 设备数据
	 * @return R
	 */
	@Operation(summary = "修改设备数据" , description = "修改设备数据" )
	@SysLog("修改设备数据" )
	@PutMapping
	@PreAuthorize("@pms.hasPermission('homecenter_hassDeviceRegistry_edit')" )
	public R updateById(@RequestBody HassDeviceRegistryEntity hassDeviceRegistry) {
		return R.ok(hassDeviceRegistryService.updateById(hassDeviceRegistry));
	}

	/**
	 * 通过id删除设备数据
	 * @param ids devId列表
	 * @return R
	 */
	@Operation(summary = "通过id删除设备数据" , description = "通过id删除设备数据" )
	@SysLog("通过id删除设备数据" )
	@DeleteMapping
	@PreAuthorize("@pms.hasPermission('homecenter_hassDeviceRegistry_del')" )
	public R removeById(@RequestBody Long[] ids) {
		return R.ok(hassDeviceRegistryService.removeBatchByIds(CollUtil.toList(ids)));
	}


	/**
	 * 导出excel 表格
	 * @param hassDeviceRegistry 查询条件
	 * @param ids 导出指定ID
	 * @return excel 文件流
	 */
	@ResponseExcel
	@GetMapping("/export")
	@PreAuthorize("@pms.hasPermission('homecenter_hassDeviceRegistry_export')" )
	public List<HassDeviceRegistryEntity> exportExcel(HassDeviceRegistryEntity hassDeviceRegistry,Long[] ids) {
		return hassDeviceRegistryService.list(Wrappers.lambdaQuery(hassDeviceRegistry).in(ArrayUtil.isNotEmpty(ids), HassDeviceRegistryEntity::getDevId, ids));
	}

	/**
	 * 导入excel 表
	 * @param hassDeviceRegistryList 对象实体列表
	 * @param bindingResult 错误信息列表
	 * @return ok fail
	 */
	@PostMapping("/import")
	@PreAuthorize("@pms.hasPermission('homecenter_hassDeviceRegistry_export')" )
	public R importExcel(@RequestExcel List<HassDeviceRegistryEntity> hassDeviceRegistryList, BindingResult bindingResult) {
		return R.ok(hassDeviceRegistryService.saveBatch(hassDeviceRegistryList));
	}

	@Operation(summary = "同步设备信息", description = "接收hass设备信息")
	@PostMapping("/pushDevices")
	public R pushDevices(@RequestBody SyncDevicesVO vo) {
		if(vo.getSuccess()){
			hassDeviceRegistryService.syncHassDeviceRegistry(vo.getResult());
		}else{
			log.info(JSON.toJSONString(vo));
		}
		return R.ok();
	}
}

